using System;
using System.Linq;
using System.Windows.Input;
using SoGame.Helper;
using SoGame.Model;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;
using System.Windows.Navigation;
using System.Windows.Threading;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Research.Kinect.Nui;
using System.Drawing.Imaging;

namespace SoGame.ViewModels
{
    public class CommandParameter
    {
        public bool CanEditBeExecuted { get; set; }
    }

    public class MainWindowViewModel : BaseViewModel
    {
        private SoGameDbContext context = new SoGameDbContext();
        private DispatcherTimer sendEmailTimer;

        /// <summary>
        /// Gets the navigate command.
        /// </summary>
        public ICommand NavigateCommand
        {
            get { return new RelayCommand<NavigationLinkInfo>(ExecuteNavigateCommand, CanExecuteNavigateCommand); }
        }

        /// <summary>
        /// Executes the navigate command.
        /// </summary>
        /// <param name="param">The param.</param>
        public void ExecuteNavigateCommand(NavigationLinkInfo param)
        {
            CurrentUri = param;
        }

        /// <summary>
        /// Determines whether this instance [can execute navigate command] the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <returns>
        ///   <c>true</c> if this instance [can execute navigate command] the specified param; otherwise, <c>false</c>.
        /// </returns>
        public bool CanExecuteNavigateCommand(NavigationLinkInfo param)
        {
            return true;
        }

        /// <summary>
        /// Gets the search command.
        /// </summary>
        public ICommand SearchCommand
        {
            get { return new BaseCommand(Search); }
        }

        /// <summary>
        /// Searches this instance.
        /// </summary>
        public void Search()
        {
            var test = context.FindPlayer(SearchText);
        }

        /// <summary>
        /// Gets the back command.
        /// </summary>
        public ICommand BackCommand
        {
            get { return new BaseCommand(Back); }
        }

        /// <summary>
        /// Backs this instance.
        /// </summary>
        public void Back()
        {
            CurrentUri = PreviousUri.LastOrDefault();
            PreviousUri.Remove(PreviousUri.LastOrDefault());
            PreviousUri.Remove(PreviousUri.LastOrDefault());
        }

        /// <summary>
        /// Refresh command.
        /// </summary>
        public ICommand RefreshCommand
        {
            get { return new BaseCommand(Refresh); }
        }

        /// <summary>
        /// Refresh menu 
        /// </summary>
        public void Refresh()
        {
            if (AllNavLinks.Where(it => it.Id == 1).FirstOrDefault() != null)
                AllNavLinks.Where(it => it.Id == 1).FirstOrDefault().NavText = string.Format("joueurs ({0})", PlayersCount);

            if (AllNavLinks.Where(it => it.Id == 4).FirstOrDefault() != null)
                AllNavLinks.Where(it => it.Id == 4).FirstOrDefault().NavText = string.Format("nouvelles parties ({0})", context.GetGamePlaysWithoutPlayer().Count());
        }

        /// <summary>
        /// Gets the players count.
        /// </summary>
        public int PlayersCount
        {
            get { return context.GetAllPlayers().Count(); }
        }

        /// <summary>
        /// Gets or sets all nav links.
        /// </summary>
        /// <value>
        /// All nav links.
        /// </value>
        public ObservableCollection<NavigationLinkInfo> AllNavLinks { get; set; }

        protected ObservableCollection<NavigationLinkInfo> _previousUri;

        /// <summary>
        /// Gets or sets the previous URI.
        /// </summary>
        /// <value>
        /// The previous URI.
        /// </value>
        public ObservableCollection<NavigationLinkInfo> PreviousUri
        {
            get { return _previousUri; }
            set
            {
                _previousUri = value;
                OnPropertyChanged(() => this.PreviousUri);
            }
        }

        protected NavigationLinkInfo _currentUri;

        /// <summary>
        /// Gets or sets the current URI.
        /// </summary>
        /// <value>
        /// The current URI.
        /// </value>
        public NavigationLinkInfo CurrentUri
        {
            get { return _currentUri; }
            set
            {
                PreviousUri.Add(_currentUri);
                _currentUri = value;
                if (this.UseKinect)
                {
                    KinectHelper.Instance.PauseKinect();
                }
                OnPropertyChanged(() => this.CurrentUri);
            }
        }

        /// <summary>
        /// Gets the players.
        /// </summary>
        public ObservableCollection<Player> Players
        {
            get
            {
                ObservableCollection<Player> players = new ObservableCollection<Player>();
                foreach (var item in context.GetAllPlayers())
                {
                    players.Add(item);
                }
                return players;
            }
        }

        private string _searchText;
        /// <summary>
        /// Gets or sets the search text.
        /// </summary>
        /// <value>
        /// The search text.
        /// </value>
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                OnPropertyChanged(() => this.SearchText);
            }
        }

        private bool _isKinectConnected;
        /// <summary>
        /// Gets or sets a value indicating whether this instance is kinect connected.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is kinect connected; otherwise, <c>false</c>.
        /// </value>
        public bool IsKinectConnected
        {
            get { return _isKinectConnected; }
            set
            {
                _isKinectConnected = value;
                this.OnPropertyChanged(() => this.IsKinectConnected);
            }
        }

        private bool isSendingMail;
        /// <summary>
        /// Gets or sets a value indicating whether this instance is sending mail.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is sending mail; otherwise, <c>false</c>.
        /// </value>
        public bool IsSendingMail {
            get { return isSendingMail; }
            set {
                if (isSendingMail != value) {
                    isSendingMail = value;
                    OnPropertyChanged(() => this.IsSendingMail);
                }
            }
        }

        private int mailsToSend;
        /// <summary>
        /// Gets or sets the mails to send.
        /// </summary>
        /// <value>
        /// The mails to send.
        /// </value>
        public int MailsToSend {
            get { return this.mailsToSend; }
            set {
                if (this.mailsToSend != value) {
                    this.mailsToSend = value;
                    OnPropertyChanged(() => this.MailsToSend);
                }
            }
        }

        private int currentMail;
        /// <summary>
        /// Gets or sets the current mail.
        /// </summary>
        /// <value>
        /// The current mail.
        /// </value>
        public int CurrentMail {
            get { return this.currentMail; }
            set {
                if (this.currentMail != value) {
                    this.currentMail = value;
                    OnPropertyChanged(() => this.currentMail);
                }
            }
        }

        private KinectStatus _kinectStatut;
        public KinectStatus KinectStatut
        {
            get
            {
                if (this.UseKinect && KinectHelper.Instance.IsKinectStarted)
                {
                    _kinectStatut = KinectHelper.Instance.Statut;
                    if (_kinectStatut == KinectStatus.Connected)
                    {
                        IsKinectConnected = true;
                    }
                    else
                    {
                        IsKinectConnected = false;
                    }
                    return _kinectStatut;
                }
                IsKinectConnected = false;
                return KinectStatus.Disconnected;   
            }
        }

        private FacebookStatus facebookStatus = FacebookStatus.Disconnected;
        /// <summary>
        /// Gets the facebook status.
        /// </summary>
        public FacebookStatus FacebookStatus {
            get { return this.facebookStatus; }
        }

        /// <summary>
        /// Gets the facebook connection command.
        /// </summary>
        public ICommand FacebookConnectionCommand {
            get {
                return new BaseCommand(() => FacebookConnect(), () => true);
            }
        }

        /// <summary>
        /// Facebooks the connect.
        /// </summary>
        public void FacebookConnect() {
            FacebookHelper.Instance.Connect();
            this.facebookStatus = FacebookHelper.Instance.Status;
            this.OnPropertyChanged(() => this.FacebookStatus);
        }

        /// <summary>
        /// Starts the kinect action.
        /// </summary>
        public void StartKinectAction()
        {
            if (!KinectHelper.Instance.IsKinectStarted)
            {
                KinectHelper.Instance.StartKinect();
            }

            this.OnPropertyChanged(() => this.KinectStatut);
        }

        /// <summary>
        /// Gets the start kinect command.
        /// </summary>
        public ICommand StartKinect {
            get { return new BaseCommand(() => StartKinectAction(), () => this.UseKinect); }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindowViewModel"/> class.
        /// </summary>
        public MainWindowViewModel()
        {
            AllNavLinks = new ObservableCollection<NavigationLinkInfo>();
            AllNavLinks.Add(new NavigationLinkInfo { Id = 1, NavText = string.Format("joueurs ({0})", PlayersCount), URI = "/SoGame;component/Views/NewPlayerView.xaml", IsFirstElement = true });
            AllNavLinks.Add(new NavigationLinkInfo { Id = 2, NavText = "top joueurs", URI = "/SoGame;component/Views/TopPlayersView.xaml" });
            AllNavLinks.Add(new NavigationLinkInfo { Id = 3, NavText = "jeux", URI = "/SoGame;component/Views/GamesView.xaml" });
            AllNavLinks.Add(new NavigationLinkInfo { Id = 4, NavText = string.Format("nouvelles parties ({0})", context.GetGamePlaysWithoutPlayer().Count()), URI = "/SoGame;component/Views/GamePlayView.xaml" });
            if (this.UseKinect)
            {
                AllNavLinks.Add(new NavigationLinkInfo { Id = 5, NavText = "scan joueur", URI = "/SoGame;component/Views/ReconnaissanceView.xaml" });
            }

            PreviousUri = new ObservableCollection<NavigationLinkInfo>();
            CurrentUri = AllNavLinks.FirstOrDefault();

            SearchText = "rechercher";

            if (this.EnableSendEmail)
            {
                sendEmailTimer = new DispatcherTimer()
                {
                    Interval = TimeSpan.FromMinutes(this.EmailInterval),
                    IsEnabled = true
                };
                sendEmailTimer.Tick += SendEmailEvent;
                sendEmailTimer.Start();
                new Thread(new ThreadStart(() => SendEmailEvent(this, EventArgs.Empty))).Start();
            }

            if (this.AutoconnectFacebook) {
                FacebookConnect();
            }

            this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainWindowViewModel_PropertyChanged);

            if(this.UseKinect)
                StartKinectAction();

            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 1, 0, 0);
            timer.Start();
        }

        void MainWindowViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SearchText") {
                if (this.SearchText.Length >= 3) {
                    this.Search();
                    this.OnPropertyChanged(() => this.Players);
                }
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            Refresh();
        }

#if (ASYNC)
        /// <summary>
        /// Sends the email event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected async void SendEmailEvent(Object sender, EventArgs e) {
            SmtpClient client = new SmtpClient(this.SmtpServer, this.SmtpPort);
            if (!string.IsNullOrEmpty(this.SmtpUser))
            {
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(this.SmtpUser, this.SmtpPassword);
            }

            foreach (var gp in this.context.GetGamePlayToBeSend()) {
                MailMessage mm = new MailMessage();
                mm.To.Add(new MailAddress(gp.Player.Email, string.Format("{0} {1}", gp.Player.FirstName, gp.Player.Name)));
                mm.From = new MailAddress(this.MailFrom, this.MailFromName);
                mm.Subject = "[TEST SoGame] Votre photo !";
                mm.Body = "bla bla bla...<br />\r\nVotre score : " + gp.Score.ToString() + "<br />\r\n<img src=\"cid:logo\"/>";
                //mm.Attachments.Add(new Attachment(@"g:\tests\logo_soat.png"));

                AlternateView av = AlternateView.CreateAlternateViewFromString(mm.Body, null, MediaTypeNames.Text.Html);
                LinkedResource lr = new LinkedResource(@"g:\tests\logo_soat.png");
                lr.ContentId = "logo";
                av.LinkedResources.Add(lr);
                mm.AlternateViews.Add(av);

                await client.SendTaskAsync(mm);

                if (gp.SentMail == null)
                {
                    gp.SentMail = new SentMail();
                    gp.SentMail.GamePlayID = gp.ID;
                    gp.SentMail.MailSend = true;
                    this.context.SaveSentMail(gp.SentMail);
                }
                else
                {
                    gp.SentMail.MailSend = true;
                    this.context.UpdateSentMail(gp.SentMail);
                }

            }
            this.context.SaveChanges(); 
            //Dispatcher.CurrentDispatcher.Invoke(new Action(delegate() { this.context.SaveChanges(); }));
        }
#else
        /// <summary>
        /// Sends the email event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void SendEmailEvent(Object sender, EventArgs e)
        {
            SmtpClient client = new SmtpClient(this.SmtpServer, this.SmtpPort);
            if (!string.IsNullOrEmpty(this.SmtpUser))
            {
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(this.SmtpUser, this.SmtpPassword);
            }

            var attachments = new Dictionary<string, LinkedResource>();
            attachments.Add("Background", new LinkedResource("Assets/Mails/background.png") { ContentId="Background" });
            attachments.Add("TextMerci", new LinkedResource("Assets/Mails/texte_merci.png") { ContentId="TextMerci" });
            attachments.Add("SoSlam", new LinkedResource("Assets/Mails/tile_soslam.png") { ContentId = "soSlam" });
            attachments.Add("SoTank", new LinkedResource("Assets/Mails/tile_sotank.png") { ContentId = "soTank" });
            attachments.Add("TileSoat", new LinkedResource("Assets/Mails/tile_soat.png") { ContentId = "TileSoat" });
            attachments.Add("TileGame", new LinkedResource("Assets/Mails/tile_game.png") { ContentId = "TileGame" });
            attachments.Add("TileText", new LinkedResource("Assets/Mails/tile_texte.png") { ContentId = "TileText" });
            attachments.Add("TileTechDays", new LinkedResource("Assets/Mails/tile_techdays.png") { ContentId = "TileTechDays" });
            attachments.Add("TextFollow", new LinkedResource("Assets/Mails/texte_follow.png") { ContentId = "TextFollow" });
            attachments.Add("TextFollowBlog", new LinkedResource("Assets/Mails/texte_follow_blog.png") { ContentId = "TextFollowBlog" });
            attachments.Add("TextFollowF", new LinkedResource("Assets/Mails/texte_follow_f.png") { ContentId = "TextFollowF" });
            attachments.Add("TextFollowT", new LinkedResource("Assets/Mails/texte_follow_t.png") { ContentId = "TextFollowT" });

            // .Where(p => (p.Item2 != null && p.Item2.SentMail == null) 
                //|| (p.Item3 != null && p.Item3.SentMail == null))
            var gpToSend = this.context.GetGamePlayToBeSend();
            this.MailsToSend = gpToSend.Count();
            this.IsSendingMail = true;
            int currentMail = 0;


            foreach (var gp in gpToSend)
            {
                this.CurrentMail = currentMail++;
                Bitmap[] soSlamImage, soTankImage;
                List<string> tempFileNames = new List<string>(4)  {
                    Path.ChangeExtension(Path.GetTempFileName(), ".jpg"),
                    Path.ChangeExtension(Path.GetTempFileName(), ".jpg"),
                    Path.ChangeExtension(Path.GetTempFileName(), ".jpg"),
                    Path.ChangeExtension(Path.GetTempFileName(), ".jpg")
                };

                soSlamImage = InitializeImage(gp.Item2);
                soTankImage = InitializeImage(gp.Item3);

                var htmlMessage = File.ReadAllText("Assets/Mails/Template_TechDays.htm");

                MailMessage mm = new MailMessage();
                mm.To.Add(new MailAddress(gp.Item1.Email, string.Format("{0} {1}", gp.Item1.FirstName, gp.Item1.Name)));
                mm.From = new MailAddress(this.MailFrom, this.MailFromName);
                mm.Subject = "Merci de votre visite sur le stand So@t";

                mm.Body = "Merci de votre participation.\r\nCe mail est au format HTML, veuillez utiliser un client de messagerie compatible.";
                mm.IsBodyHtml = true;
                //mm.Attachments.Add(new Attachment(@"g:\tests\logo_soat.png"));

                // Score SoSlam
                if (gp.Item2 != null && gp.Item2.Photo != null)
                {
                    var path = GenerateScoreImage(gp.Item2.Score, "soslam");
                    if (attachments.ContainsKey("soSlamScore"))
                    {
                        attachments.Remove("soSlamScore");
                    }
                    attachments.Add("soSlamScore", new LinkedResource(path, "image/png"));
                    attachments["soSlamScore"].ContentId = "soSlamScore";
                    htmlMessage = htmlMessage.Replace("{scoreSoSlam}", "<img src=\"cid:soSlamScore\" style=\"top:0;left:0;width:173px;height:173px;z-index:99;\"/>");
                }
                else
                {
                    htmlMessage = htmlMessage.Replace("{scoreSoSlam}", "&nbsp;");
                }

                // Score SoTank
                if (gp.Item3 != null && gp.Item3.Photo != null)
                {
                    var path = GenerateScoreImage(gp.Item3.Score, "sotank");
                    if (attachments.ContainsKey("SoTankScore"))
                    {
                        attachments.Remove("SoTankScore");
                    }
                    attachments.Add("SoTankScore", new LinkedResource(path, "image/png"));
                    attachments["SoTankScore"].ContentId = "SoTankScore";
                    htmlMessage = htmlMessage.Replace("{scoreSoTank}", "<img src=\"cid:SoTankScore\"/>");

                    //htmlMessage = htmlMessage.Replace("{scoreSoTank}", "<div class=\"score\">" + gp.Item3.Score.ToString() + "</div>");
                }
                else
                {
                    htmlMessage = htmlMessage.Replace("{scoreSoTank}", "&nbsp;");
                }

                AlternateView av = AlternateView.CreateAlternateViewFromString(htmlMessage, null, MediaTypeNames.Text.Html);
                

                #region Attachement des images au mails
                av.LinkedResources.Add(attachments["Background"]);
                av.LinkedResources.Add(attachments["TextMerci"]);
                av.LinkedResources.Add(attachments["TileSoat"]);
                av.LinkedResources.Add(attachments["TileGame"]);
                av.LinkedResources.Add(attachments["TileText"]);
                av.LinkedResources.Add(attachments["TextFollow"]);
                av.LinkedResources.Add(attachments["TileTechDays"]);
                av.LinkedResources.Add(attachments["TextFollowBlog"]);
                av.LinkedResources.Add(attachments["TextFollowF"]);
                av.LinkedResources.Add(attachments["TextFollowT"]);

                if (attachments.ContainsKey("soTankScore"))
                {
                    av.LinkedResources.Add(attachments["soTankScore"]);
                }
                if (attachments.ContainsKey("soSlamScore"))
                {
                    av.LinkedResources.Add(attachments["soSlamScore"]);
                }

                if (soSlamImage != null)
                {
                    
                    soSlamImage[0].Save(tempFileNames[0]);
                    soSlamImage[1].Save(tempFileNames[1]);

                    //if (File.Exists(tempFileNames[0]) && File.Exists(tempFileNames[1]))
                    //{
                        mm.Attachments.Add(new Attachment(tempFileNames[1], "image/jpeg"));
                        var soSlamLr = new LinkedResource(tempFileNames[0], "image/jpeg");
                        soSlamLr.ContentId = "soSlam";
                        av.LinkedResources.Add(soSlamLr);
                    //}
                }
                else {
                    av.LinkedResources.Add(attachments["SoSlam"]);
                }

                if (soTankImage != null)
                {
                    try
                    {

                            soTankImage[0].Save(tempFileNames[2]);
                            soTankImage[1].Save(tempFileNames[3]);
                    }
                    finally { }

                    //if (File.Exists(tempFileNames[2]) && File.Exists(tempFileNames[3]))
                    //{
                        mm.Attachments.Add(new Attachment(tempFileNames[3], "image/jpeg"));
                        var soTankLr = new LinkedResource(tempFileNames[2], "image/jpeg");
                        soTankLr.ContentId = "soTank";
                        av.LinkedResources.Add(soTankLr);
                    //}
                }
                else {
                    av.LinkedResources.Add(attachments["SoTank"]);
                }
                #endregion

                mm.AlternateViews.Add(av);

                try
                {
                    //client.Timeout = 60;
                    try
                    {
                        client.Send(mm);
                    }
                    catch (Exception ex) {
                        return;
                    }

                    UpdateSentMail(gp.Item2);
                    UpdateSentMail(gp.Item3);

                    //try
                    //{
                    //    //tempFileNames.ForEach(f => File.Delete(f));
                    //}
                    //finally { }

//#if (DEBUG)
//                    return;
//#endif
                }
                catch {
                    return;
                }
                this.context.SaveChanges();

                if (soSlamImage != null && soSlamImage.Length > 0)
                {
                    soSlamImage.Where(i => i != null).ToList().ForEach(i => i.Dispose());
                }
                if (soTankImage != null && soTankImage.Length > 0)
                {
                    soTankImage.Where(i => i != null).ToList().ForEach(i => i.Dispose());
                }
            }
            this.IsSendingMail = false;
            //Dispatcher.CurrentDispatcher.Invoke(new Action(delegate() { this.context.SaveChanges(); }));
        }

        /// <summary>
        /// Initializes the image.
        /// </summary>
        /// <param name="gamePlay">The game play.</param>
        /// <returns></returns>
        private Bitmap[] InitializeImage(GamePlay gamePlay)
        {
            if (gamePlay == null || gamePlay.Photo == null)
            {
                return null;
            }

            Bitmap[] ret = new Bitmap[2];
            ret[1] = Bitmap.FromStream(new MemoryStream(gamePlay.Photo)) as Bitmap;
            ret[0] = new Bitmap(ret[1], new Size(173, 173));


            return ret;
        }

        /// <summary>
        /// Generates the score image.
        /// </summary>
        /// <param name="score">The score.</param>
        /// <returns></returns>
        private string GenerateScoreImage(int score, string game) {
            var fileName = Path.ChangeExtension(Path.GetTempFileName(), ".png");
            using (var image = new Bitmap(173, 173))
            {
                game = game.ToUpper() + ":";
                var fontTitle = new Font("Segoe WP Light", 11F, FontStyle.Bold); // 16px : 1em, 15px : 0.938;
                var fontScore = new Font("Segoe WP Light", 12F, FontStyle.Regular);

                using (var g = Graphics.FromImage(image))
                {
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                    g.Clear(Color.Transparent);
                    g.FillRectangle(new SolidBrush(Color.FromArgb(100, Color.White)), new Rectangle(new Point(0, 123), new Size(173, 50)));

                    var sizeTitle = g.MeasureString(game, fontTitle);
                    g.DrawString(game, fontTitle, new SolidBrush(Color.White), new PointF(4, 127));

                    var sizeScore = g.MeasureString(score.ToString(), fontScore);
                    g.DrawString("Votre score : " + score.ToString(), fontTitle, new SolidBrush(Color.White), new PointF(4, 131 + sizeTitle.Height));

                    //g.DrawString
                    //g.DrawString(score.ToString(), font, new SolidBrush(Color.White), new PointF((173F - size.Width) / 2F, 123 + (50F - size.Height)));


                }

                //image.MakeTransparent();
                image.Save(fileName, ImageFormat.Png);
            }

            return fileName;
        }

        /// <summary>
        /// Updates the sent mail.
        /// </summary>
        /// <param name="gamePlay">The game play.</param>
        private void UpdateSentMail(GamePlay gamePlay)
        {
            if (gamePlay == null) {
                return;
            }
            if (gamePlay.SentMail == null)
            {
                var sentMail = new SentMail();
                sentMail.GamePlayID = gamePlay.ID;
                sentMail.MailSend = true;
                sentMail.SendTime = DateTime.Now;
                this.context.SaveSentMail(sentMail);
            }
            else if (!gamePlay.SentMail.MailSend)
            {
                gamePlay.SentMail.MailSend = true;
                gamePlay.SentMail.SendTime = DateTime.Now;
                this.context.UpdateSentMail(gamePlay.SentMail);
            }
            this.context.SaveChanges();
        }

#endif
    }
}
